<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
error_reporting(E_ERROR | E_PARSE);
/**
 * 检测是否登录
 * @return boolean 是否登录
 */

function is_login()
{
//    $auth = array(
//        'adminid' => 1,
//        'username' => 'huang',
//        'depar_id' => 1,
//    );
//    session('admin_user', $auth);
    if (!empty(session('admin_user.adminid'))) {
        return session('admin_user.adminid');
    } else {
        return 0;
    }
}

/**
 * 获取人员的登录信息
 * @return bool|mixed
 * @author: Huang
 */
function getUserInfo()
{
    if (is_login()) {
        return session('admin_user');
    } else {
        return false;
    }
}

/*移动端判断*/
function isMobile()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA'])) {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}

/**
 * 检测当前用户是否为管理员
 * @param $uid
 * @return boolean true-管理员，false-非管理员
 */
function is_administrator($uid = null)
{
    $uid = is_null($uid) ? is_login() : $uid;
    return $uid && ( in_array(intval($uid),config('admin.auth')['not_check_id']));
}


/**
 *  * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $pk 主建
 * @param string $child
 * @param int $root
 * @return array
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree 原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array $list 过渡用的中间数组，
 * @return array        返回排过序的列表数组
 */
function tree_to_list($tree, $child = '_child', $order = 'id', &$list = array())
{
    if (is_array($tree)) {
        foreach ($tree as $key => $value) {
            $reffer = $value;
            if (isset($reffer[$child])) {
                unset($reffer[$child]);
                tree_to_list($value[$child], $child, $order, $list);
            }
            $list[] = $reffer;
        }
        $list = list_sort_by($list, $order, $sortby = 'asc');
    }
    return $list;
}

/**
 * 对查询结果集进行排序
 * @access public
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param string $sortby 排序类型
 * asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by($list, $field, $sortby = 'asc')
{
    if (is_array($list)) {
        $refer = $resultSet = array();
        foreach ($list as $i => $data)
            $refer[$i] = &$data[$field];
        switch ($sortby) {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc':// 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ($refer as $key => $val)
            $resultSet[] = &$list[$key];
        return $resultSet;
    }
    return false;
}

/**
 *获取浏览器的类型
 * @return string
 */
function getBrowser()
{
    $agent = $_SERVER["HTTP_USER_AGENT"];
    if (strpos($agent, 'MSIE') !== false || strpos($agent, 'rv:11.0')) //ie11判断
        return "ie";
    else if (strpos($agent, 'Firefox') !== false)
        return "firefox";
    else if (strpos($agent, 'Chrome') !== false)
        return "chrome";
    else if (strpos($agent, 'Opera') !== false)
        return 'opera';
    else if ((strpos($agent, 'Chrome') == false) && strpos($agent, 'Safari') !== false)
        return 'safari';
    else
        return 'unknown';
}

/**
 * 返回按层级加前缀的菜单数组
 * @author  rainfer
 * @param array|mixed $menu 待处理菜单数组
 * @param string $id_field 主键id字段名
 * @param string $pid_field 父级字段名
 * @param string $lefthtml 前缀
 * @param int $pid 父级id
 * @param int $lvl 当前lv
 * @param int $leftpin 左侧距离
 * @return array
 */
function menu_left($menu, $id_field = 'id', $pid_field = 'pid', $lefthtml = '─', $pid = 0, $lvl = 0, $leftpin = 0)
{
    $arr = array();
    foreach ($menu as $v) {
        if ($v[$pid_field] == $pid) {
            $v['lvl'] = $lvl + 1;
            $v['leftpin'] = $leftpin;
            $v['lefthtml'] = '├' . str_repeat($lefthtml, $lvl);
            $arr[] = $v;
            $arr = array_merge($arr, menu_left($menu, $id_field, $pid_field, $lefthtml, $v[$id_field], $lvl + 1, $leftpin + 20));
        }
    }
    return $arr;
}


/**  将时间控件的字符串转为数组
 * @param $timeString
 * @return array
 */
function time_StrToArr($timeString)
{
    list($start, $end) = explode('~', $timeString);
    $start = strtotime($start);
    $end = strtotime($end) + 86399;
    $time = [$start, $end];
    return $time;
}

/**
 * 获取当前request参数数组,去除值为空
 * @return array
 */
function get_query()
{
    $param = request()->except(['s']);
    $rst = array();
    foreach ($param as $k => $v) {
        if (!empty($v)) {
            $rst[$k] = $v;
        }
    }
    return $rst;
}

/**
 * 获取当前访问的完整URL地址
 */
function get_current_url()
{
    $url = 'http://';
    if (isset ($_SERVER ['HTTPS']) && $_SERVER ['HTTPS'] == 'on') {
        $url = 'https://';
    }
    if ($_SERVER ['SERVER_PORT'] != '80') {
        $url .= $_SERVER ['HTTP_HOST'] . ':' . $_SERVER ['SERVER_PORT'] . $_SERVER ['REQUEST_URI'];
    } else {
        $url .= $_SERVER ['HTTP_HOST'] . $_SERVER ['REQUEST_URI'];
    }
//    // 兼容后面的参数组装
//    if (stripos ( $url, '?' ) === false) {
//        $url .= '?t=' . time ();
//    }
    return $url;
}


/**
 *  修改操作记录日志的详细信息
 * @param   array $olddata 修改之前的数据
 * @param   array $newdata 修改的数据
 * @param   array $tablename 修改的数据库
 * @return string
 */
function getlogdetail($olddata, $newdata, $tablename)
{
    $model = model($tablename);
    $tablename = 'jtds_' . $tablename;
    $field = \think\Db::table('INFORMATION_SCHEMA.Columns')
        ->field('COLUMN_NAME', 'column_comment')
        ->where('table_name', $tablename)->cache(600)
        ->column('column_comment', 'COLUMN_NAME');
    $data = array_intersect_assoc($olddata, $newdata);//共同的部分 键值和键名都相等的时候
    $old = array_diff_assoc($olddata, $data);//老的数据键值和键名都相等的时候
    $new = array_diff_assoc($newdata, $data);//新的数据键值和键名都相等的时候
    $str = '';
    foreach ($new as $k => $v) {
        if (strpos($k, '_')) {
            $tempfun = array_reduce(explode('_', $k), function ($carry, $item) {
                $carry = ucfirst($carry) . ucfirst($item);
                return $carry;
            });
            if (method_exists($model, 'get' . $tempfun . 'TextAttr')) {
                $v = getIntToText($model, $tempfun, $new);
            }
        }
        if (method_exists($model, 'get' . ucfirst($k) . 'TextAttr')) {
            $v = getIntToText($model, $k, $new);
        }
        if (in_array($k, $model->time)) {
            $v = time_format($v);
        }
        if (empty($old[$k])) {
            $str .= "<span style='color: #9f191f;'>新增 </span>&nbsp;【$field[$k]】&nbsp;：<b>$v</b><br/>";
        } else {
            $oldv = $old[$k];
            if (method_exists($model, 'get' . ucfirst($k) . 'TextAttr')) {
                $oldv = getIntToText($model, $k, $olddata);
            }
            if (in_array($k, $model->time)) {
                $oldv = time_format($olddata[$k]);
            }
            $str .= "<span style='color: #1AAD19;'>修改</span>【$field[$k]】：由&nbsp;<b>$oldv</b>&nbsp;修改为&nbsp;<b>{$v}</b>;<br/>";
        }
    }
    if (empty($str)) return '无修改！';
    return $str;
}

/**
 * 订单日志新增
 * @param $actiondata ['actionname'=>操作名称, 'khd'=>操作端 ，'order_id'=>订单id 'state'=>订单状态]
 * @param $olddata 老数据
 * @param $newdata 新数据
 * @param $tablename 表名称
 */
function addOrderLog($actiondata, $olddata, $newdata, $tablename)
{
    $data['remark'] = getlogdetail($olddata, $newdata, $tablename);
    $userinfo = getUserInfo();
    $data['czaction'] = $actiondata['actionname'];
    $data['order_id'] = $actiondata['order_id'];
    $data['khd'] = is_wechat_browser() ? 2 : 1;
    if ($actiondata['actionname'] == 12) {
        $data['depar_id'] = $newdata['jd_depar'];
        $data['czry'] = $newdata['jdry'];
        $data['actionname'] = 12;
    } else {
        if(empty($userinfo['depar_id'])){  //微信端添加
            $userAll = session('weixinuser');
            $data['depar_id'] = $userAll['depar_id'];//建单部门
            $data['czry'] = $userAll['id'];
            $data['logimg'] = $userAll['avatar'];
        }else{
            $data['depar_id'] = $userinfo['depar_id'];
            $data['czry'] = $userinfo['adminid'];
            $data['logimg'] = $userinfo['avatar'];
        }
    }
    $data['state'] = $actiondata['state'];
    $orderlog = new \app\admin\model\Order_log();
    $orderlog->log($data);
}

/**
 * 获取值
 * @param $model
 * @param $k
 * @param $new
 * @return mixed
 * @author: Huang
 */
function getIntToText($model, $k, $new)
{
    $tempfun = 'get' . ucfirst($k) . 'TextAttr';

    $v = $model->$tempfun('', $new);
    return $v;
}


/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @param string $format
 * @return false|string
 * @author: Huang
 */
function time_format($time = NULL, $format = 'Y-m-d H:i')
{
    $time = $time === NULL ? time() : intval($time);
    return date($format, $time);
}

/**
 * 隐藏电话、微信或QQ (支持微信号、qq号、邮箱、手机号)
 * @param $info
 * @return mixed|string
 */
function hidInfo($info)
{
    $data = explode('@', $info);
    if (count($data) == 1) {//不是邮箱
        $IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i', $info); //固定电话
        if ($IsWhat == 1) {
            return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i', '$1****$2', $info);
        } elseif (strlen($info) == 11) { //11位  电话号码或其他号码
            return preg_replace('/(1[0-9]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $info);
        } else {
            return preg_replace('/([0-9]{3})[0-9]*([0-9]{3,})/', '$1****$2', $data[0]);
        }
    } else {//数字邮箱
        return preg_replace('/([0-9]{3})[0-9]*([0-9]{3,})/', '$1****$2', $data[0]) . '@' . $data[1];
    }
}

/**
 * 判断是否处在微信浏览器内
 */
function is_wechat_browser()
{
    $agent = $_SERVER ['HTTP_USER_AGENT'];
    if (!strpos($agent, "icroMessenger")) {
        return false;
    }
    return true;
}

/**
 *  截取中文字符串
 * @param $str
 * @param int $start
 * @param $length
 * @param string $charset
 * @param bool $suffix
 * @return string
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
{
    if (function_exists("mb_substr")) {
        $slice = mb_substr($str, $start, $length, $charset);
    } elseif (function_exists('iconv_substr')) {
        $slice = iconv_substr($str, $start, $length, $charset);
    } else {
        $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
        $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
        $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
        $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
    }
    $fix = '';
    if (strlen($slice) < strlen($str)) {
        $fix = '...';
    }
    return $suffix ? $slice . $fix : $slice;
}

/*
 * 读取excel文件到数组
 * @param string $filename,excel文件名（含路径）
 * @param string $type,excel文件类型 'Excel2007', 'Excel5', 'Excel2003XML','OOCalc', 'SYLK', 'Gnumeric', 'HTML','CSV'
 * @return array
 */
function read($filename)
{
    $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    if ($extension == 'xlsx') {
        $type = 'Excel2007';
    } else if ($extension == 'xls') {
        $type = 'Excel5';
    } else if ($extension == 'csv') {
        $type = 'CSV';
    }
    $objReader = \PHPExcel_IOFactory::createReader($type);
    $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');
    $objWorksheet = $objPHPExcel->getActiveSheet();
    $highestRow = $objWorksheet->getHighestRow();
    $highestColumn = $objWorksheet->getHighestColumn();
    $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
    $excelData = array();
    for ($row = 1; $row <= $highestRow; $row++) {
        for ($col = 0; $col < $highestColumnIndex; $col++) {
            $excelData[$row][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
        }
    }
    return $excelData;
}

/**
 * 导入文件
 * @param $file_name
 * @return PHPExcel
 * @author: Huang
 */
function daoruexcel($file_name)
{
    ini_set('memory_limit','2048M');
    $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    if ($extension == 'xlsx') {
        $type = 'Excel2007';
    } else if ($extension == 'xls') {
        $type = 'Excel5';
    } else if ($extension == 'csv') {
        $type = 'CSV';
    } else {
        $type = 'Excel5';
    }
    try {
//        $objReader = \PHPExcel_IOFactory::createReader($type);
        $objReader = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name);
        return $objReader;
    } catch (Exception $exception) {
        return ['code' => 0, 'msg' => $exception->getMessage()];
    }

}

/**
 * 导入excel转换成 array
 * @param $filename 完整的路径名
 * @param int $i 从第几行开始读取
 * @return array
 * @author: Huang
 */
function excelToArray($filename, $i = 2)
{
    $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    if ($extension == 'xlsx') {
        $type = 'Excel2007';
    } else if ($extension == 'xls') {
        $type = 'Excel5';
    } else if ($extension == 'csv') {
        $type = 'CSV';
    }
    //加载excel文件
    $objReader = \PHPExcel_IOFactory::createReader($type);
    $objPHPExcelReader = $objReader->load($filename, $encode = 'utf-8');
    $reader = $objPHPExcelReader->getWorksheetIterator();
    //循环读取sheet
    foreach ($reader as $sheet) {
        //读取表内容
        $content = $sheet->getRowIterator();
        //逐行处理
        $res_arr = array();
        foreach ($content as $key => $items) {
            $rows = $items->getRowIndex();              //行
            $columns = $items->getCellIterator();       //列
            $row_arr = array();
            //确定从哪一行开始读取
            if ($rows < $i) {
                continue;
            }
            //逐列读取
            foreach ($columns as $head => $cell) {
                //获取cell中数据
                $data = $cell->getValue();
                $row_arr[] = $data;
            }
            $res_arr[] = $row_arr;
        }
    }
    return $res_arr;
}

/**
 * 数组层级缩进转换
 * @param array $array 源数组
 * @param int $pid
 * @param int $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1)
{
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[] = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }

    return $list;
}

/**
 * 构建层级（树状）数组
 * @param array $array 要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid_name 父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid_name = 'pid', $child_key_name = 'children')
{
    $counter = array_children_count($array, $pid_name);
    if (!isset($counter[0]) || $counter[0] == 0) {
        return $array;
    }
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);
        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid_name] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid_name], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid_name);
    }

    return $tree;
}

/**
 * 子元素计数器
 * @param array $array
 * @param int $pid
 * @return array
 */
function array_children_count($array, $pid)
{
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}

/**
 * 获取分类所有子分类
 * @param int $cid 分类ID
 * @return array|bool
 */
function get_category_children($cid)
{
    if (empty($cid)) {
        return false;
    }

    $children = Db::name('category')->where(['path' => ['like', "%,{$cid},%"]])->select();

    return array2tree($children);
}

//推荐订单日志
function addLog($data)
{
    $data['create_time'] = time();
    \think\Db::name('zjslog')->insert($data);
}

//时间转换：转换成年月日星期时分   中文形式
function changeTime($time)
{
    $time = strtotime($time);
//    $time = intval($time);
    $today = [
        mktime(0, 0, 0, date('m'), date('d'), date('Y')),
        mktime(23, 59, 59, date('m'), date('d'), date('Y'))
    ];
    $tomorrow = [
        mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')),
        mktime(23, 59, 59, date('m'), date('d') + 1, date('Y'))
    ];
    $weeks = [
        strtotime(date('Y-m-d', strtotime("+0 week Monday", time()))),
        strtotime(date('Y-m-d', strtotime("+0 week Sunday", time()))) + 24 * 3600 - 1
    ];
    $day = date("Y年m月d日", $time);//日
    if (date('H', $time) >= 12) {
        $shifen = '下午' . date("H:i", $time);
    } else {
        $shifen = '上午' . date("H:i", $time);
    }
    if ($time >= $today[0] && $time <= $today[1]) {
        return "{$day}(今天){$shifen}";
    }
    if ($time >= $tomorrow[0] && $time <= $tomorrow[1]) {
        return "{$day}(明天){$shifen}";
    }
    if ($time >= $weeks[0] && $time <= $weeks[1]) {
        return "{$day}(本周" . mb_substr('日一二三四五六', date('w', $time), 1, 'utf-8') . "){$shifen}";
    } else {
        return "{$day}(星期" . mb_substr('日一二三四五六', date('w', $time), 1, 'utf-8') . "){$shifen}";//2017年5月19日（星期五）11点00分
    }
}

/**
 * 列出本地目录的文件
 * @author rainfer <81818832@qq.com>
 * @param string $path
 * @param string $pattern
 * @return array
 */
function list_file($path, $pattern = '*')
{
    if (strpos($pattern, '|') !== false) {
        $patterns = explode('|', $pattern);
    } else {
        $patterns [0] = $pattern;
    }
    $i = 0;
    $dir = array();
    if (is_dir($path)) {
        $path = rtrim($path, '/') . '/';
    }
    foreach ($patterns as $pattern) {
        $list = glob($path . $pattern);
        if ($list !== false) {
            foreach ($list as $file) {
                $dir [$i] ['filename'] = basename($file);
                $dir [$i] ['path'] = dirname($file);
                $dir [$i] ['pathname'] = realpath($file);
                $dir [$i] ['owner'] = fileowner($file);
                $dir [$i] ['perms'] = substr(base_convert(fileperms($file), 10, 8), -4);
                $dir [$i] ['atime'] = fileatime($file);
                $dir [$i] ['ctime'] = filectime($file);
                $dir [$i] ['mtime'] = filemtime($file);
                $dir [$i] ['size'] = filesize($file);
                $dir [$i] ['type'] = filetype($file);
                $dir [$i] ['ext'] = is_file($file) ? strtolower(substr(strrchr(basename($file), '.'), 1)) : '';
                $dir [$i] ['isDir'] = is_dir($file);
                $dir [$i] ['isFile'] = is_file($file);
                $dir [$i] ['isLink'] = is_link($file);
                $dir [$i] ['isReadable'] = is_readable($file);
                $dir [$i] ['isWritable'] = is_writable($file);
                $i++;
            }
        }
    }
    $cmp_func = create_function('$a,$b', '
		if( ($a["isDir"] && $b["isDir"]) || (!$a["isDir"] && !$b["isDir"]) ){
			return  $a["filename"]>$b["filename"]?1:-1;
		}else{
			if($a["isDir"]){
				return -1;
			}else if($b["isDir"]){
				return 1;
			}
			if($a["filename"]  ==  $b["filename"])  return  0;
			return  $a["filename"]>$b["filename"]?-1:1;
		}
		');
    usort($dir, $cmp_func);
    return $dir;
}

/**
 * 删除目录及目录下所有文件或删除指定文件
 * @param str $path 待删除目录路径
 * @param bool $delDir 是否删除目录，1或true删除目录，0或false则只删除文件保留目录（包含子目录）
 * @return bool 返回删除状态
 */
function delDirAndFile($path, $delDir = FALSE)
{
    $handle = opendir($path);
    if ($handle) {
        while (false !== ($item = readdir($handle))) {
            if ($item != "." && $item != "..")
                is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
        }
        closedir($handle);
        if ($delDir)
            return rmdir($path);
    } else {
        if (file_exists($path)) {
            return unlink($path);
        } else {
            return FALSE;
        }
    }
}


/**
 * post模拟请求
 * @param $url
 * @param $data
 * @return mixed|string
 */
function vpost($url, $data)
{ // 模拟提交数据函数
    $curl = curl_init();  // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
//    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
//    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $tmpInfo = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        return curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $tmpInfo; // 返回数据
}


/**
 * 将角色状态组取出转化为数组
 * @param $states
 * @param $key
 * @return array
 */
function strToArr($states, $key)
{
    $str = '';
    foreach ($states as $val) {
        if ($val[$key] != '') {
            $str .= $val[$key] . ',';
        }
    }
    if ($str == '') {
        return $str;
    } else {
        return array_unique(explode(',', substr($str, 0, strlen($str) - 1)));//去重
    }
}


/**
 * 处理数组中指定某些字段隐藏信息(目前支持一维和二维数组)
 * @param  array $data
 * @param  string /array  $keys  需要加密的字段
 * @param  array $condition 状态限制条件
 * @param  string $uid 当前登录者的id  针对邀约主管
 * @return array
 */
function doData($data, $condition = [], $uid = '', $kefu = '', $keys = ['maphone', 'otherphone', 'weixin', 'qq'])
{
    if (is_string($keys)) {
        $keys = explode(',', $keys);
    }
    $data = $data->append(['state_text', 'qdxx_text', 'yyxx_text', 'kcxx_text', 'lbxx_text', 'bumen_text', 'area_text', 'hszt_text', 'yykf_text', 'jdry_text', 'hsmd_text', 'yycg_text', 'khd_text', 'operation_text', 'czry_text'])->toArray();
    if (empty($condition)) {
        $condition = [];
    }
    $condition = (array)$condition;
    foreach ($data as $key => $value) {
        if (is_array($value)) {//二维数组
            foreach ($value as $k => $v) {
                if (empty($uid) || $value[$kefu] != $uid) {
                    foreach ($keys as $keyarr) {
                        if (empty($condition)) {
                            if ($k == $keyarr) {
                                $data[$key][$k] = hidInfo($v);
                            }
                        } else {
                            if ($k == $keyarr && in_array($data[$key]['ywstate'], $condition)) {
                                $data[$key][$k] = hidInfo($v);
                            }
                        }
                    }
                }
            }
        } else {//一维数组
            if (empty($uid) || $value[$kefu] != $uid) {
                foreach ($keys as $keyarr) {
                    if (empty($condition)) {
                        if ($key == $keyarr) {
                            $data[$key] = hidInfo($value);
                        }
                    } else {
                        if ($key == $keyarr && in_array($data['ywstate'], $condition)) {
                            $data[$key] = hidInfo($value);
                        }
                    }
                }
            }
        }
    }
    return $data;
}

/**
 * 判断浏览器是否为ie
 * @return bool
 */
function isIeBrowser()
{
    $str = getBrowser();
    if ('ie' == getBrowser()) {
        return true;
    }
    return false;
}

/**
 * 递归扫描文件夹
 * @param string $dir
 * @return array
 */
function scandirs($dir)
{
    $result = [];
    $cdir = scandir($dir);
    foreach ($cdir as $value) {
        if (!in_array($value, array(".", ".."))) {
            if (is_dir($dir . DS . $value)) {
                $result[$value] = scandirs($dir . DS . $value);
            } else {
                $result[] = $value;
            }
        }
    }
    return $result;
}

/**
 * 根据id 得到部门名称
 * @param $id
 * @return mixed
 * @author: Huang
 */
function getDeparText($id){
    $depar = \think\Db::name('depar')->where('status',1)->cache(600)->column('name','id');
    return $depar[$id];
}

/**
 * 根据id获取职位名称
 * @param $id
 * @return mixed
 * @author: Huang
 */
function getPositionText($id){
    $depar = \think\Db::name('position')->where('status',1)->cache(600)->column('title','id');
    return $depar[$id];
}


/**
 * 操作日志
 * @param $id
 * @param $msg
 */
function logdaily($id, $username,$msg)
{
//    $name = getUserInfo();

    $arr['executor'] = $username;//操作者名字
    $arr['action'] = doActive($id);//操作动作
    $arr['executor_time'] = date("Y-m-d H:i:s", time());//操作时间
    $arr['remarks'] = $msg;//操着备注
    $arr['user_ip'] = request()->ip();//操作者客户端ip

//    dump($id);
//    dump($username);
//    dump($arr);
    \think\Db::name('daily')->insert($arr);
}

/**
 * 操作动作
 * @param $id
 * @return mixed
 */
function doActive($id)
{
    $item = [
        1 => '登录', 2 => "退出登录", 3 => "添加用户", 4 => "修改用户", 5 => "删除用户",
        6 => "添加角色",7 => "编辑角色",8 => "删除角色",9 => "添加部门", 10 => "编辑部门",
        11 => "删除部门",
//          9 => "新增会员", 10 => "编辑会员",
//        11 => "禁用会员", 12 => "添加渠道组", 13 => "编辑渠道组", 14 => "删除渠道组",
//        15 => "新增状态", 16 => "编辑状态", 17 => "添加活动", 18 => "编辑活动", 19 => "删除活动",
//        20 => "编辑类别", 21 => "删除类别", 22 => "添加类别", 23 => "修改密码", 24 => "修改来源",
//        25 => "添加活动", 26 => "编辑活动", 27 => "删除活动", 28 => "清除缓存", 29 => "添加来源", 30 => "编辑来源", 31 => "删除来源",
//         33 => "添加职位", 34 => "编辑职位", 35 => "删除职位",
    ];
    //操作动作
    if (is_int($id)) {
        return $item[$id];
    } else {
        return $item[(int)$id];
    }
}

/**
 * 清除富文本css样式
 * @param $content
 * @return string
 * @author: wu
 */
function clearRichText($content){
    $content_01 = $content;//从数据库获取富文本content
    $content_02 = htmlspecialchars_decode($content_01);//把一些预定义的 HTML 实体转换为字符
    $content_03 = str_replace("&nbsp;","",$content_02);//将空格替换成空
    $contents = strip_tags($content_03);//函数剥去字符串中的 HTML、XML 以及 PHP 的标签,获取纯文本内容
    $con = mb_substr($contents, 0, 100,"utf-8");//返回字符串中的前100字符串长度的字符
    return $con;
}

/**
 * 将时间转成文本显示，并且处理初始时间
 * @param $time
 * @param string $timeFormat
 * @return bool|string
 */
function formatTime($time, $timeFormat = 'Y-m-d H:i:s')
{
    if (is_integer($time)) {
        $time = date($timeFormat, $time);
    }
    if (strpos($time, '1970-01') !== false) {
        $time = '';
    }
    return $time;
}